# coding: utf-8
# 18-11-21 下午5:01

from captcha.generator import DefaultGenerator, SimpleGenerator
from django.conf import settings
import uuid
import random
import os
import datetime


class Captcha():
    @classmethod
    def _create_captcha(cls, captcha_code):
        generator = DefaultGenerator()
        captcha = generator.make_captcha(string=captcha_code)
        _uuid = str(uuid.uuid4())
        filename = 'code/' + datetime.datetime.now().strftime('%Y-%m') + '/' + _uuid + '.png'
        filepath = settings.STATIC_ROOT + filename
        fileurl = settings.STATIC_URL + filename
        filedir = os.path.dirname(filepath)
        if not os.path.exists(filedir):
            # 如果没有文件夹，先创建
            os.makedirs(filedir)
        captcha.save(filepath)
        return fileurl, _uuid

    @classmethod
    def _create_captcha_code(cls):
        '''
        随机captcha
        :return:
        '''
        hack = 'acefhjkmorstxyz'
        hack += 'ABCDEFHJKNOPQRSTUXYZ'
        return ''.join(random.choices(hack, k=4))

    @classmethod
    def get_captcha(cls):
        captcha_code = cls._create_captcha_code()
        fileurl, _uuid = cls._create_captcha(captcha_code)
        return {'code': captcha_code.lower(), 'url': fileurl, 'uuid': _uuid}

captcha_cls = Captcha()
